<template>
  <basic-container class="production-page">
    <el-row :gutter="20">
      <el-col :span="8" style="min-width: 300px">
        <div class="bindLeft" v-loading="bindLeftLoading" element-loading-text="条码信息查找中，请稍后..." element-loading-spinner="el-icon-loading">
          <h2>条码信息</h2>
          <avue-form ref="barCodeForm" v-model="barCode" :option="barCodeOption" @reset-change="emptytChange" @submit="submit"> </avue-form>
        </div>
      </el-col>
      <el-col :span="16">
        <h2>包装绑定信息</h2>
        <avue-crud
          :option="option"
          :table-loading="loading"
          :data="data"
          v-model="form"
          ref="crud"
          @row-update="rowUpdate"
          @selection-change="selectionChange"
          @size-change="sizeChange"
          @on-load="onLoad"
        >
          <template slot="menuLeft">
            <el-button type="primary" size="small" icon="el-icon-unlock" v-if="permission.packagingUnbinding_unbinding" @click="handleUnlock">解绑</el-button>
          </template>
        </avue-crud>
      </el-col>
    </el-row>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>
<script>
import { checkPacking, getProductInfoByPackSn, getSnInfo, packingUnbound } from '@/api/product/packagingUnbinding';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { mapGetters } from 'vuex';
export default {
  name: 'ProductPackagingUnbinding',
  components: { GlobalModalTemplate },
  inject: ['globalStartLoad', 'globalEndLoad'],
  data() {
    return {
      productId: '',
      barCode: {},
      barCodeOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 200,
        column: [
          {
            label: '包装条码/产品序列号',
            prop: 'sequenceNumber',
            span: 24,
            rules: [
              {
                required: true,
                message: '包装条码/产品序列号',
                trigger: 'blur'
              }
            ],
            enter: (value) => {
              this.searchScanBarCode(value);
            }
          },
          // {
          //   label: '工单号',
          //   disabled: true,
          //   span: 24,
          //   prop: 'workOrderNo'
          // },
          {
            label: '产品编码',
            disabled: true,
            span: 24,
            prop: 'partNo'
          },
          {
            label: '产品名称',
            disabled: true,
            span: 24,
            prop: 'partName'
          },
          {
            label: '产品型号',
            disabled: true,
            span: 24,
            prop: 'partModel'
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            disabled: true,
            span: 24
          }
        ]
      },
      data: [],
      form: {},
      query: {},
      bindLeftLoading: false,
      loading: false,
      selectionList: [],
      option: {
        height: 'calc(100vh - 289px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: false,
        addBtn: false,
        editBtn: false,
        delBtn: false,
        refreshBtn: false,
        columnBtn: true,
        selection: true,
        dialogClickModal: false,
        menu: false,
        labelWidth: 120,
        column: [
          {
            label: '产品序列号',
            prop: 'sequenceNumber',
            width: 250
          },
          {
            label: '包装条码',
            prop: 'packNo',
            width: 250
          },
          {
            label: '包装时间',
            prop: 'packedDate'
          },
          {
            label: '包装人',
            prop: 'packName'
          }
        ]
      },
      visibile: false,
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      timer: new Date().getTime() //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
    };
  },
  computed: {
    ...mapGetters(['permission'])
  },
  methods: {
    // 查找条码
    searchScanBarCode(value) {
      if (!this.barCode.sequenceNumber) {
        this.$message.warning('请输入扫描条码');
        return false;
      }
      this.bindLeftLoading = true;
      getProductInfoByPackSn(this.barCode.sequenceNumber)
        .then((res) => {
          this.barCodeDetail = res.data.data;
          if (res.data.data.length) {
            this.getFormData(res.data.data[0].sequenceNumber);
          }
          this.selectionClear();
          this.onLoad();
        })
        .catch(() => {})
        .finally(() => {
          this.bindLeftLoading = false;
        });
    },
    async getFormData(sequenceNumber) {
      try {
        const res = await getSnInfo(sequenceNumber);
        const form = res.data.data;
        Object.assign(this.barCode, { partNo: form.partNo, partName: form.partName, partModel: form.partModel, workOrderNo: form.workOrderNo });
      } catch (e) {
        console.log(e);
      }
    },
    handleUnlock() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('是否解除所选序列号和包装的绑定关系?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let list = this.selectionList.map((s) => {
          return { packId: s.packId, productId: s.id, packingSpecification: s.packingSpecification };
        });
        packingUnbound(list)
          .then((res) => {
            this.$message({
              type: 'success',
              message: '解绑成功!'
            });
            console.log(this.selectionList, this.data);
            this._forEach(this.selectionList, (item) => {
              let index = this._findIndex(this.data, { id: item.id });
              if (index != -1) {
                this.data.splice(index, 1);
              }
            });
          })
          .catch(() => {});
      });
    },
    onLoad(params = {}) {
      this._forEach(this.barCodeDetail, (item) => {
        let indexOne = this._findIndex(this.data, { sequenceNumber: item.sequenceNumber });
        if (indexOne === -1) {
          let indexTwo = this._findIndex(this.data, { sequenceNumber: item.sequenceNumber });
          if (indexTwo != -1) {
            this.data.splice(indexTwo, 0, item);
          } else {
            this.data.unshift(item);
          }
        }
      });
      this.$nextTick(() => {
        this.$refs.crud.toggleSelection(this.data);
      });
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 生产订单
        case 'workOrder':
          this.modalName = 'workOrderModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择工单信息（双击进行选择）',
            url: '/api/mes-product/work-order/page',
            titleInfo: 'workOrderModal',
            isPage: true,
            rowSelectionType: 'single',
            menu: false,
            editBtn: false,
            menuWidth: 100,
            searchLabelWidth: 90,
            templateName: 'WORKORDER'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderModal':
          this.barCode.workOrderNo = this._get(rowData, 'orderNo', '');
          this.barCode.workOrderId = this._get(rowData, 'id', '');
          this.barCode.partNo = this._get(rowData, 'partNo', '');
          this.barCode.partName = this._get(rowData, 'partName', '');
          this.barCode.partModel = this._get(rowData, 'partModel', '');
          this.barCode.smtm = '';
          setTimeout(() => {
            this.data = [];
          }, 500);
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>
<style lang="scss" scoped>
.packagingUnbindingPage {
  display: flex;
  .bindLeft {
    width: 20%;
    min-width: 300px;
    margin-right: 20px;
  }
  .bindRight {
    flex: 1;
  }
}
::v-deep .el-card .is-never-shadow {
  padding: 0 !important;
}
</style>
